<template>
  <view class="game-container">
    <!-- 顶部信息 -->
    <view class="game-header">
      <view class="score-box">
        <text class="score-label">当前积分</text>
        <text class="score-value">{{ score }}</text>
      </view>
      <button class="reset-btn" @tap="resetGame">
        <text class="bi bi-arrow-clockwise"></text> 重新开始
      </button>
      <!-- <button class="reset-btn" @tap="resetScore">
        <text class="bi bi-arrow-clockwise"></text> 积分清零
      </button> -->
    </view>

    <!-- 鼓励文字 -->
    <view class="encourage-text animate__animated" :class="encourageClass">
      {{ encourageText }}
    </view>

    <!-- 游戏区域 -->
    <view class="game-board">
      <view 
        v-for="(block, index) in gameBlocks" 
        :key="block.id"
        class="game-block"
        @click="addToBottomSlots(block)"
        :style="{ 
          transform: `translate3d(${block.x}rpx, ${block.y}rpx, 0)`,
          zIndex: block.zIndex
        }"
      >
        <text class="block-text">{{ block.name }}{{ block.years }}</text>
      </view>
    </view>

    <!-- 底部放置区域 -->
    <view class="bottom-area">
      <view 
        v-for="(slot, index) in bottomSlots" 
        :key="index"
        class="slot"
        :class="{ 'active': isSlotActive(index) }"
      >
        <text v-if="slot">{{ slot.name }}</text>
        <text v-else>空</text>
      </view>
    </view>

    <!-- 游戏说明 -->
    <view class="game-instructions">
      <view class="instruction-title">
        <text class="bi bi-info-circle"></text> 游戏玩法
      </view>
      <view class="instruction-list">
        <view class="instruction-item">
          <text class="bullet">1.</text>
          <text>点击上方的物理学家方块将其填充到下方槽位</text>
        </view>
        <view class="instruction-item">
          <text class="bullet">2.</text>
          <text>集齐三个相同的物理学家名称可消除</text>
        </view>
        <view class="instruction-item">
          <text class="bullet">3.</text>
          <text>下方槽位最多容纳6个方块</text>
        </view>
        <view class="instruction-item">
          <text class="bullet">4.</text>
          <text>槽位装满未能消除则游戏结束</text>
        </view>
        <view class="instruction-item">
          <text class="bullet">5.</text>
          <text>每次消除可获得10积分</text>
        </view>
        <view class="instruction-item">
          <text class="bullet">6.</text>
          <text>通关可额外获得50积分奖励</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { useCounterStore } from '@/stores/counter'
const userStore = useUserStore()
const store = useCounterStore()
const score = computed(() => userStore.userInfo?.score || 0)
const resetScore = () => {
  userStore.updateUserScore(0)
}
// 游戏数据
const gameBlocks = ref([])
const bottomSlots = ref(Array(6).fill(null))
const encourageText = ref('开始寻找相同的物理学家名称吧！')
const encourageClass = ref('')

// 鼓励文字库
const encourageTexts = {
  start: ['开始寻找相同的物理学家名称吧！', '让我们一起探索物理学家！'],
  match: ['太棒了！', '好眼力！', '完美配对！', '继续加油！'],
  combo: ['连击！真厉害！', '太强了！', '你太懂物理学家了！'],
  fail: ['别灰心，再试一次！', '慢慢来，总会成功的！']
}

// 初始化游戏
const initGame = () => {
  const blocks = []
  const maskNames = store.giantsList.map(info => info.name)
  
  // 创建30个方块（确保有可以消除的组合）
  for (let i = 0; i < 30; i++) {
    const name = maskNames[Math.floor(i / 3) % maskNames.length]
    blocks.push({
      id: i,
      name,
      x: Math.random() * 300 + 100, // 随机生成 x 坐标，限制在 100 到 400 之间
      y: Math.random() * 300 + 100, // 随机生成 y 坐标，限制在 100 到 400 之间
      zIndex: 1,
      matched: false
    })
  }
  
  gameBlocks.value = blocks
  bottomSlots.value = Array(6).fill(null)
  showEncourageText('start')
}

// 点击方块添加到底部槽位
const addToBottomSlots = (block) => {
  // 找到第一个空位
  const emptyIndex = bottomSlots.value.findIndex(slot => slot === null)
  if (emptyIndex === -1) {
    // 槽位已满，游戏失败
    gameOver()
    return
  }
  
  // 添加到槽位
  bottomSlots.value[emptyIndex] = {
    id: block.id,
    name: block.name
  }
  
  // 移除原方块
  const blockIndex = gameBlocks.value.findIndex(b => b.id === block.id)
  if (blockIndex !== -1) {
    gameBlocks.value.splice(blockIndex, 1)
  }
  
  // 检查是否可以消除
  checkMatch()
}

// 检查匹配
const checkMatch = () => {
  const slots = bottomSlots.value
  let matchStart = -1
  
  // 查找连续三个相同的
  for (let i = 0; i < slots.length - 2; i++) {
    if (slots[i] && slots[i+1] && slots[i+2] &&
        slots[i].name === slots[i+1].name && 
        slots[i].name === slots[i+2].name) {
      matchStart = i
      break
    }
  }
  
  // 如果找到匹配
  if (matchStart !== -1) {
    // 消除匹配的三个
    for (let i = 0; i < 3; i++) {
      bottomSlots.value[matchStart + i] = null
    }
    
    // 将后面的方块前移
    bottomSlots.value = bottomSlots.value.filter(slot => slot !== null)
    while (bottomSlots.value.length < 6) {
      bottomSlots.value.push(null)
    }
    
    // 增加积分
    userStore.updateUserScore(10)
    
    // 显示鼓励文字
    showEncourageText('match')
    
    // 检查是否胜利
    if (gameBlocks.value.length === 0 && bottomSlots.value.every(slot => slot === null)) {
      showCongratulations()
    }
  }
}

// 显示鼓励文字
const showEncourageText = (type) => {
  const texts = encourageTexts[type]
  encourageText.value = texts[Math.floor(Math.random() * texts.length)]
  encourageClass.value = 'animate__bounceIn'
  
  setTimeout(() => {
    encourageClass.value = ''
  }, 1000)
}

// 游戏结束
const gameOver = () => {
  uni.showModal({
    title: '游戏结束',
    content: '槽位已满，游戏结束！要重新开始吗？',
    confirmText: '重新开始',
    success: (res) => {
      if (res.confirm) {
        resetGame()
      }
    }
  })
}

// 显示祝贺弹窗
const showCongratulations = () => {
  uni.showModal({
    title: '恭喜通关！',
    content: '你真是太厉害了！获得额外50积分奖励！',
    showCancel: false,
    success: () => {
      userStore.updateUserScore(50)
      resetGame()
    }
  })
}

// 重置游戏
const resetGame = () => {
  initGame()
}

// 判断槽位是否激活
const isSlotActive = (index) => {
  return bottomSlots.value[index] !== null
}

// 初始化游戏
onMounted(() => {
  initGame()
})
</script>

<style lang="scss" scoped>
.game-container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 40rpx;
  position: relative;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.score-box {
  background: #fff;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  
  .score-label {
    font-size: 28rpx;
    color: #666;
    margin-right: 20rpx;
  }
  
  .score-value {
    font-size: 32rpx;
    font-weight: bold;
    color: var(--td-brand-color);
  }
}

.reset-btn {
  display: flex;
  align-items: center;
  gap: 10rpx;
  background: var(--td-brand-color);
  color: #fff;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
  
  &:active {
    opacity: 0.9;
  }
}

.encourage-text {
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: var(--td-brand-color);
  margin: 30rpx 0;
  min-height: 50rpx;
}

.game-board {
  position: relative;
  height: 800rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  margin-bottom: 40rpx;
  overflow: hidden;
}

.game-block {
  width: 120rpx;
  height: 120rpx;
  background: #fff;
  border: 4rpx solid var(--td-brand-color);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: bold;
  color: var(--td-brand-color);
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.block-text {
  pointer-events: none;
  user-select: none;
  -webkit-user-select: none;
}

.bottom-area {
  position: fixed;
  bottom: 40rpx;
  left: 40rpx;
  right: 40rpx;
  height: 160rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 0 20rpx;
}

.slot {
  width: 100rpx;
  height: 100rpx;
  border: 2rpx dashed #ccc;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: var(--td-brand-color);
  
  &.active {
    border: 2rpx solid var(--td-brand-color);
    background: rgba(var(--td-brand-color-rgb), 0.1);
  }
}

.game-instructions {
  padding: 30rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.instruction-title {
  font-size: 32rpx;
  font-weight: bold;
  color: var(--td-brand-color);
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.instruction-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.instruction-item {
  display: flex;
  align-items: flex-start;
  gap: 10rpx;
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  
  .bullet {
    color: var(--td-brand-color);
    font-weight: bold;
    min-width: 40rpx;
  }
}

@import 'animate.css';
</style> 